<script setup>

import { ref } from "vue";
import { uploadInstrumentImage, returnInstrument } from "@/apps/client/utils/instrumentApi.js";
import { getUserInfo } from "@/apps/client/utils/userApi.js";
import {
  showNotify,
  showToast,
  closeToast,
  showLoadingToast
} from "vant";
import {useRouter} from "vue-router";

const router = useRouter()
const loan = JSON.parse(sessionStorage.getItem("returnInstrument"));
console.log(loan)
// 页面返回
const onClickLeft = () => router.back();

// 表单字段
const instrumentName = ref('');
const returnImgs = ref([]);         // base64预览图
const returnImageUrls = ref([]);    // 用于提交的 URL 列表
const message = ref('');
const userPoints = ref('');

// 获取用户积分信息
getUserInfo().then(({ data }) => {
  userPoints.value = data.points + "积分";
  sessionStorage.setItem("points", data.points);
});

// 上传图片后处理
const afterRead = async (file) => {
  //returnImgs.value.push(file.content); // base64 预览

  try {
    const res = await uploadInstrumentImage(file);
    if (res["code"] === 200 && res.data.url) {
      returnImageUrls.value.push(res.data.url);
    } else {
      showNotify({ type: 'danger', message: '图片上传失败' });
    }
  } catch (err) {
    showNotify({ type: 'danger', message: '上传错误：' + err.message });
  }
};

// 提交归还
async function submitReturnForm() {

  if (returnImageUrls.value.length === 0) {
    return showNotify({ message: '请上传至少一张归还照片' });
  }

  showLoadingToast({ message: '提交中...', forbidClick: true, duration: 0 });

  const payload = {
    id: loan.id,
    returnImgs: returnImageUrls.value,
  };

  try {
    const res = await returnInstrument(payload);
    if (res.code === 200) {
      showNotify({ type: 'success', message: '归还成功' });

      const { data } = await getUserInfo();
      userPoints.value = data.points + "积分";
      sessionStorage.setItem("points", data.points);
      router.back()
    } else {
      showNotify({ message: res.msg || '归还失败' });
    }
  } catch (err) {
    showToast(err.message || '提交失败，请稍后重试');
  } finally {
    closeToast();
  }
}
</script>

<template>
  <div style="background: #EEEEEE7F; min-height: 100vh">
    <van-nav-bar title="仪器归还" left-text="返回" left-arrow @click-left="onClickLeft" />

    <van-space direction="vertical" fill>
      <van-cell-group inset style="margin-top: 8px">
        <van-cell title="仪器名称" :value="loan.instrumentName" size="large" />
        <van-cell title="借用时间" :value="loan.borrowTime" size="large" />
        <van-cell title="归还位置" :value="loan['returnFloorName'] + ' ' + loan['returnRoomNumber']" size="large" />
        <van-cell title="仪器照片"/>
        <van-image
            width="150"
            height="150"
            :src="`/api/src/img/${loan.instrumentImgs[0]}`"
            style="margin: 0 16px"
        />

        <van-cell title="归还照片" />
        <van-uploader
            v-model="returnImgs"
            :after-read="afterRead"
            multiple
            max-count="8"
            preview-image
            style="margin: 0 16px"
        />
      </van-cell-group>

<!--      <van-cell-group inset>-->
<!--        <van-field-->
<!--            v-model="message"-->
<!--            rows="2"-->
<!--            autosize-->
<!--            label="备注"-->
<!--            type="textarea"-->
<!--            maxlength="50"-->
<!--            placeholder="请输入备注"-->
<!--            show-word-limit-->
<!--        />-->
<!--      </van-cell-group>-->

      <div style="width: auto; margin: 0 16px 8px 16px">
        <van-button round type="primary" style="width: 100%;" @click="submitReturnForm">
          提交归还
        </van-button>
      </div>
    </van-space>
  </div>
</template>

<style scoped>
</style>
